import { useState } from 'react'
import { Card, Table, Button, Space, Tag, Modal, message, Input, Tabs, Tooltip } from 'antd'
import { EyeOutlined, CheckOutlined, CloseOutlined, DownloadOutlined } from '@ant-design/icons'
import './index.scss'

const { TextArea } = Input

const CommentManagement = () => {
  const [loading, setLoading] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [detailVisible, setDetailVisible] = useState(false)
  const [currentComment, setCurrentComment] = useState(null)
  const [rejectVisible, setRejectVisible] = useState(false)
  const [rejectReason, setRejectReason] = useState('')
  const [activeTab, setActiveTab] = useState('all')

  // 模拟数据
  const [dataSource, setDataSource] = useState([
    {
      id: 1,
      userName: '张三',
      targetType: '笔记',
      targetTitle: '《活着》读后感',
      content: '写得很好，深有同感！',
      status: 'pending',
      createTime: '2024-01-20 10:30:00',
      parentComment: null,
    },
    {
      id: 2,
      userName: '李四',
      targetType: '书评',
      targetTitle: '百年孤独：魔幻现实主义的巅峰',
      content: '分析得很透彻，让我对这本书有了新的理解。',
      status: 'approved',
      createTime: '2024-01-19 15:20:00',
      parentComment: null,
    },
    {
      id: 3,
      userName: '王五',
      targetType: '笔记',
      targetTitle: '《三体》科幻世界观',
      content: '黑暗森林法则确实令人震撼！',
      status: 'pending',
      createTime: '2024-01-18 09:15:00',
      parentComment: null,
    },
    {
      id: 4,
      userName: '赵六',
      targetType: '书评',
      targetTitle: '平凡的世界：平凡中的伟大',
      content: '这个评价太主观了吧',
      status: 'rejected',
      rejectReason: '评论内容不友善，存在攻击性',
      createTime: '2024-01-17 14:45:00',
      parentComment: null,
    },
    {
      id: 5,
      userName: '钱七',
      targetType: '笔记',
      targetTitle: '《1984》反乌托邦思考',
      content: '同意楼上的观点，这本书值得反复阅读。',
      status: 'approved',
      createTime: '2024-01-16 11:20:00',
      parentComment: '张三的评论',
    },
  ])

  // 状态标签配置
  const statusConfig = {
    pending: { text: '待审核', color: 'orange' },
    approved: { text: '已通过', color: 'green' },
    rejected: { text: '已拒绝', color: 'red' },
  }

  // 类型标签配置
  const typeConfig = {
    '笔记': { color: 'blue' },
    '书评': { color: 'purple' },
  }

  // 查看详情
  const handleViewDetail = (record) => {
    setCurrentComment(record)
    setDetailVisible(true)
  }

  // 通过审核
  const handleApprove = (record) => {
    Modal.confirm({
      title: '确认通过',
      content: `确定通过用户"${record.userName}"的评论吗？`,
      onOk: () => {
        setDataSource(prev =>
          prev.map(item =>
            item.id === record.id ? { ...item, status: 'approved' } : item
          )
        )
        message.success('审核通过')
      },
    })
  }

  // 拒绝审核
  const handleReject = (record) => {
    setCurrentComment(record)
    setRejectVisible(true)
  }

  // 确认拒绝
  const confirmReject = () => {
    if (!rejectReason.trim()) {
      message.warning('请输入拒绝原因')
      return
    }
    
    if (currentComment?.isBatch) {
      // 批量拒绝
      setDataSource(prev =>
        prev.map(item =>
          selectedRowKeys.includes(item.id)
            ? { ...item, status: 'rejected', rejectReason }
            : item
        )
      )
      setSelectedRowKeys([])
      message.success(`已拒绝 ${selectedRowKeys.length} 条评论`)
    } else {
      // 单个拒绝
      setDataSource(prev =>
        prev.map(item =>
          item.id === currentComment.id
            ? { ...item, status: 'rejected', rejectReason }
            : item
        )
      )
      message.success('已拒绝该评论')
    }
    
    setRejectVisible(false)
    setRejectReason('')
  }

  // 批量通过
  const handleBatchApprove = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要审核的评论')
      return
    }
    Modal.confirm({
      title: '批量通过',
      content: `确定通过选中的 ${selectedRowKeys.length} 条评论吗？`,
      onOk: () => {
        setDataSource(prev =>
          prev.map(item =>
            selectedRowKeys.includes(item.id) ? { ...item, status: 'approved' } : item
          )
        )
        setSelectedRowKeys([])
        message.success('批量审核通过')
      },
    })
  }

  // 批量拒绝
  const handleBatchReject = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要拒绝的评论')
      return
    }
    setRejectVisible(true)
    setCurrentComment({ isBatch: true })
  }

  // 导出数据
  const handleExport = () => {
    message.success('开始导出数据')
  }

  // 根据Tab筛选数据
  const filteredData = dataSource.filter(item => {
    if (activeTab === 'all') return true
    return item.status === activeTab
  })

  // 统计各状态数量
  const getStatusCount = (status) => {
    if (status === 'all') return dataSource.length
    return dataSource.filter(item => item.status === status).length
  }

  const columns = [
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
      width: 100,
    },
    {
      title: '评论对象',
      key: 'target',
      width: 250,
      render: (_, record) => (
        <div>
          <Tag color={typeConfig[record.targetType].color} style={{ marginBottom: 4 }}>
            {record.targetType}
          </Tag>
          <div style={{ fontSize: 13, color: '#595959' }}>{record.targetTitle}</div>
        </div>
      ),
    },
    {
      title: '评论内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text}>
          <div className="comment-content">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '回复对象',
      dataIndex: 'parentComment',
      key: 'parentComment',
      width: 120,
      render: (text) => text || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={statusConfig[status].color}>
          {statusConfig[status].text}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            >
              详情
            </Button>
          </Tooltip>
          {record.status === 'pending' && (
            <>
              <Tooltip title="通过">
                <Button
                  type="link"
                  size="small"
                  icon={<CheckOutlined />}
                  style={{ color: '#52c41a' }}
                  onClick={() => handleApprove(record)}
                >
                  通过
                </Button>
              </Tooltip>
              <Button
                type="link"
                size="small"
                icon={<CloseOutlined />}
                danger
                onClick={() => handleReject(record)}
              >
                拒绝
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ]

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  }

  return (
    <div className="comment-management-container">
      <Card className="table-card">
        <div className="tabs-header">
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            className="status-tabs"
            items={[
              {
                key: 'all',
                label: `全部 (${getStatusCount('all')})`,
              },
              {
                key: 'pending',
                label: `待审核 (${getStatusCount('pending')})`,
              },
              {
                key: 'approved',
                label: `已通过 (${getStatusCount('approved')})`,
              },
              {
                key: 'rejected',
                label: `已拒绝 (${getStatusCount('rejected')})`,
              },
            ]}
          />
          <div className="tabs-actions">
            <Space>
              <Button
                type="primary"
                icon={<CheckOutlined />}
                onClick={handleBatchApprove}
                disabled={selectedRowKeys.length === 0 || activeTab !== 'pending'}
              >
                批量通过
              </Button>
              <Button
                danger
                icon={<CloseOutlined />}
                onClick={handleBatchReject}
                disabled={selectedRowKeys.length === 0 || activeTab !== 'pending'}
              >
                批量拒绝
              </Button>
              <Button icon={<DownloadOutlined />} onClick={handleExport}>
                导出数据
              </Button>
            </Space>
          </div>
        </div>

        {selectedRowKeys.length > 0 && (
          <div className="selection-bar">
            <span className="selection-info">
              已选择 {selectedRowKeys.length} 项
            </span>
          </div>
        )}

        <Table
          rowSelection={{
            ...rowSelection,
            getCheckboxProps: (record) => ({
              disabled: record.status !== 'pending',
            }),
          }}
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            total: filteredData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
        />
      </Card>

      {/* 详情弹窗 */}
      <Modal
        title="评论详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)}>
            关闭
          </Button>,
          currentComment?.status === 'pending' && (
            <Button
              key="approve"
              type="primary"
              icon={<CheckOutlined />}
              onClick={() => {
                handleApprove(currentComment)
                setDetailVisible(false)
              }}
            >
              通过
            </Button>
          ),
          currentComment?.status === 'pending' && (
            <Button
              key="reject"
              danger
              icon={<CloseOutlined />}
              onClick={() => {
                setDetailVisible(false)
                handleReject(currentComment)
              }}
            >
              拒绝
            </Button>
          ),
        ]}
        width={700}
      >
        {currentComment && (
          <div className="comment-detail">
            <div className="detail-item">
              <label>用户：</label>
              <span>{currentComment.userName}</span>
            </div>
            <div className="detail-item">
              <label>评论对象：</label>
              <div>
                <Tag color={typeConfig[currentComment.targetType].color}>
                  {currentComment.targetType}
                </Tag>
                <span style={{ marginLeft: 8 }}>{currentComment.targetTitle}</span>
              </div>
            </div>
            {currentComment.parentComment && (
              <div className="detail-item">
                <label>回复对象：</label>
                <span>{currentComment.parentComment}</span>
              </div>
            )}
            <div className="detail-item">
              <label>评论内容：</label>
              <div className="comment-full-content">{currentComment.content}</div>
            </div>
            <div className="detail-item">
              <label>状态：</label>
              <Tag color={statusConfig[currentComment.status].color}>
                {statusConfig[currentComment.status].text}
              </Tag>
            </div>
            {currentComment.rejectReason && (
              <div className="detail-item">
                <label>拒绝原因：</label>
                <div className="reject-reason">{currentComment.rejectReason}</div>
              </div>
            )}
            <div className="detail-item">
              <label>创建时间：</label>
              <span>{currentComment.createTime}</span>
            </div>
          </div>
        )}
      </Modal>

      {/* 拒绝原因弹窗 */}
      <Modal
        title="拒绝评论"
        open={rejectVisible}
        onOk={confirmReject}
        onCancel={() => {
          setRejectVisible(false)
          setRejectReason('')
        }}
        okText="确定"
        cancelText="取消"
      >
        <div style={{ marginBottom: 16 }}>
          <p>请输入拒绝原因：</p>
          <TextArea
            rows={4}
            value={rejectReason}
            onChange={(e) => setRejectReason(e.target.value)}
            placeholder="请详细说明拒绝的原因，以便用户改进..."
            maxLength={200}
            showCount
          />
        </div>
      </Modal>
    </div>
  )
}

export default CommentManagement
